/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: BearingServer.cpp,v 1.4 2009-11-16 10:32:16 ray Exp $
 *
 * \file
 * \brief Implementation of Bearing interface Server.
 * \author Mikko Elomaa <mikko.elomaa@tkk.fi>
 *
 */

#include "BearingServer.hpp"
#include "BearingData.hpp"

//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
using namespace MaCI::Bearing;
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CBearingServer::CBearingServer(MaCICtrl::CMaCICtrlServer *aMaCICtrlServerPtr, 
                           const int aInterfaceMinor,
                           const std::string &aDescription,
                           const std::string &aInstanceName)
  : CMaCI(aMaCICtrlServerPtr, GIMI_PROTOCOL_MACI_BEARING, aInterfaceMinor, aInstanceName),
    //    CSync(1,1),
    //    CThread(1),
    iServerActive(false),
    iServiceDescription(aDescription),
    iBearingSequenceNumber(0)
{
}
//*****************************************************************************

CBearingServer::~CBearingServer()
{
  DoClose();
}
//*****************************************************************************

MaCI::EMaCIError CBearingServer::DoOpen(void)
{
  EMaCIError result = KMaCIError;
  assert(this != NULL);
  assert(iGIMIPtr != NULL);
  
  // Execute only if server is not active.
  if (!iServerActive) {
    // Register service.
    RegisterProvidedService("MaCI-BearingServer; '" + iServiceDescription + "'");
    RegisterAcceptedService("MaCI-BearingServer-Cmd; '" + iServiceDescription + "'");
    
    // Start the handler Thread
    iServerActive = true;
    //    CThread::RunThread();
    
    result = KMaCIOK;
    
    dPrint(4,"Succesfully Open():ed BearingServer instance %p.", this);
  }
    
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CBearingServer::DoClose(void)
{
  EMaCIError result = KMaCIError;
  assert(this != NULL);
  assert(iGIMIPtr != NULL);

  // Execute block only if server is currently active.
  if (iServerActive) {
    // Stop!
    iServerActive = false;

    // Stop the handler Thread
    //    /* CThread::CancelThread(); //Removed by script */
    //    CThread::WaitThread();    

    // Unregister services
    UnregisterProvidedService();
    UnregisterAcceptedService();
    
    dPrint(4,"Succesfully Close():ed BearingServer instance %p", this);
  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CBearingServer::SendBearingEvent(const CBearingData &aBearingData)
{
  EMaCIError result = KMaCIError;
  
  if (iServerActive) {
    if (aBearingData.GetBearingEvent()) {
      // Update sequence.
      ++iBearingSequenceNumber;
      
      // Got
      SendInterfaceSubscriberMessage(aBearingData.GetBinBagContainerPtr()->GetBuffer(),
                                     aBearingData.GetBinBagContainerPtr()->GetBufferSize(),
                                     iBearingSequenceNumber);

      dPrint(10,"SendInterfaceSubscriberMessage called: %d:%d, seq: %d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             iBearingSequenceNumber-1,
             aBearingData.GetBinBagContainerPtr()->GetBufferSize());
      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'BearingEvent' element in provided CBearingData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send BearingData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }

  return result;
}
//*****************************************************************************

MaCI::EMaCIError CBearingServer::SendReply(const CBearingData &aData, 
                                         const SMessageSource &aSource)
{
  EMaCIError result = KMaCIError;

  // Check that server is active.
  if (iServerActive) {

    // Check that there is a data structure
    if (&aData!=NULL) {
      dPrint(2,"Sending reply");
      // Send
      result = SendSynchronousMessageReply(aData.GetBinBagContainerPtr()->GetBuffer(),
                                           aData.GetBinBagContainerPtr()->GetBufferSize(),
                                           aSource);
    
    } else {
      dPrint(2,"No 'RechargerEvent' element in provided CRechargerData object. Will not send!");
      result = KMaCIInvalidFormat;
      
    }
    
  } else {
    dPrint(2,"Unable to send RechargerData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;
    
  }

  return result;
}
//*****************************************************************************

MaCI::EMaCIError CBearingServer::WaitCommand(CBearingData &aData, SMessageSource &aSource,
                                           const unsigned int aTimeout_ms)
{
  EMaCIError result;
  gimi::GIMIMessage gmsg;

  // Call the ReceiveMessage wrapper with 2s timeout
  result = ReceiveInterfaceMessage(gmsg, aTimeout_ms);
  
  // If result is OK, process the msg.
  if (result == KMaCIOK && IsInterfaceAccess(gmsg.getSenderId())) {
    bool r;
    gim::binbag::CBinBag bb;
    CBearingData d;

    // Decode BinBag.
    r = bb.Decode(gmsg.getData(), gmsg.getDatalength());
    if (r) {
      // BinBag OK. Decode BearingData.
      r = d.DecodeFrom(&bb);
      if (r) {
        // BearingData ok. Copy to caller.
        aData.Copy(d);

        // Copy source info too.
        aSource = gmsg;

      } else {
        result = KMaCIInvalidFormat;
      }

    } else {
      result = KMaCIInvalidFormat;
    }
  }
  
  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
/*
int CBearingServer::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CBearingData d;
  bool r;
  
  // Before even attempting to decode, read access.
  MaCICtrl::TAccess a;
  CMaCI::GetMaCICtrlServer()->GetAccessInfo(a, 
                                            iInterfaceMajor,
                                            iInterfaceMinor,
                                            msg.getSenderId(),
                                            true);
  
  // Test for access.
  if (a.IsAccess()) {
    dPrint(8,"Access granted for nodeID: %08X, proceed with command.",
           msg.getSenderId());

    r = bb.Decode(msg.getData(), msg.getDatalength());
    if (r) {
      // Succesfully decoded as BinBag.
      r = d.DecodeFrom(&bb);
      if (r) {
        // Succesfully decoded as SpeedCtrl
        // Now, Check whether it was Command, if so, process it and construct reply
        gim::binbag::CBinBag replybb;
        CBearingData reply;
        bool send_reply = false;

        // Do encoding to this binbag
        reply.EncodeTo(&replybb);
      
        const TCommand *cmd = d.GetCommand();
        if (cmd) {
          switch(cmd->cmd) {
          
            // Set Commands: by default passed to user
          case KCommandGetSourceInfoArray:
            Lock();
            reply.SetCommand(TCommand(KCommandSetSourceInfoArray));
            reply.SetTimestamp(Common::TTimestamp());
            for(EACH_IN_i(iSourceInfoMap)) {
              reply.AddSourceInfo(i->second);
            }
            Unlock();
            send_reply = true;
            break;

          case KCommandNewBearing:
            dPrint(4,"Nothing to do on CommandNewBearing :)");
            break;
            
          default:
            dPrint(4,"Unidentified command! %d (%x)! Ignore.",
                   cmd->cmd, cmd->cmd);
            break;
          }
        }
        
        // Check whether reply needs to be sent
        if (send_reply) {
          int gr = iGIMIPtr->send(msg.getSenderId(),
                                  replybb.GetBuffer(),
                                  replybb.GetBufferSize(),
                                  iInterfaceMajor,
                                  iInterfaceMinor,
                                  msg.messageId); // Reply with same ID
          if (gr == GIMI_OK) {
            dPrint(10,"Succesfully sent message with %d BinBag elements to '%p'",
                   replybb.GetElementCount(),
                   msg.getSenderId());

          } else {
	  
            dPrint(8,"Failed to send message with %d BinBag elements to '%p'",
                   replybb.GetElementCount(),
                   msg.getSenderId());
          }
        }
      }
    }
  } else {
    dPrint(2,"Access denied for nodeID: %08X, will not execute command.",
           msg.getSenderId());
    
  }  
  return result;
}
*/
//*****************************************************************************
/*
int CBearingServer::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(iServerActive) {
    // Call the ReceiveMessage wrapper with 2s timeout
    e = ReceiveInterfaceMessage(gmsg, 2000);

    if (e == KMaCIOK) {
      dPrint(8,"Got GIMIMessage %d - Processing.", gmsg.messageId);
      ProcessMessage(gmsg);
      
    } else if (e != KMaCITimeout) {
      // Other error than Timeout!  This is fatal, so bailing out!
      // Leave the ServerActive flag set, as it is in closing phase.
      break;
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");

  return result;
}
*/
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

